import * as THREE from "three";
import { threeViewStore } from "../../store/models/data";
import pinia from '../../store/index';
var moveFlag = false;
const store = threeViewStore(pinia);
export default function pickPoint(pickPointVis) {
    let domContainer = document.getElementById("threeContainer");
    if (pickPointVis) {

        domContainer.style.cursor = "crosshair";
        domContainer?.addEventListener("mousedown", onmousedown);
        window.controls.addEventListener("change", onPointerMove);
        domContainer?.addEventListener("mouseup", pickClick);
    }
    else {
        domContainer.style.cursor = "default";
        domContainer?.removeEventListener("mouseup", pickClick);
        domContainer?.removeEventListener("mousedown", onmousedown);
        window.controls.removeEventListener("change", onPointerMove);
    }
}
let labelText = document.createElement('span');
let vposition: THREE.Vector3;
let geometryArr: any = [];
function pickClick(event: any) {
    if (!moveFlag) {
        if (geometryArr.length > 0) {
            labelText.innerHTML = '';
            
            geometryArr.forEach((item: any, index: any) => {
                    window.threeScene.remove(item);
                geometryArr =[];
            })
        }
        const pointer = new THREE.Vector2();
        pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
        pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
        // 得到的pointer是三维坐标
        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(pointer, window.camera);
        let position = [];
        const intersects = raycaster.intersectObjects(window.threeScene.children, true);
        if (intersects.length > 0) {
            let index = 0;
            let x = intersects[index].point.x;
            let y = intersects[index].point.y;
            let z = intersects[index].point.z;
            position.push(x);
            position.push(y);
            position.push(z);
            vposition = intersects[0].point;
            labelText.innerHTML = `(${vposition.x.toFixed(2)},${vposition.y.toFixed(2)},${vposition.z.toFixed(2)})`;
            // pointsArrV3.push(vposition);
        }
        // 绘制点
        const geometry = new THREE.BufferGeometry();
        const color = new Float32Array([1, 0, 0]);
        geometry.setAttribute('position', new THREE.Float32BufferAttribute(position, 3));
        geometry.setAttribute('color', new THREE.BufferAttribute(color, 3));
        geometry.computeBoundingSphere();
        // 定义材质
        // 如果需要绘制点线可以被模型遮挡，把depthTest设置为true即可
        const material = new THREE.PointsMaterial({ size: 0.1, vertexColors: true, depthTest: false });
        const drawpoint = new THREE.Points(geometry, material);
        window.threeScene.add(drawpoint);
        geometryArr.push(drawpoint);
        drawLabel(drawpoint, event);

    }
}
// 鼠标按下
function onmousedown() {
    moveFlag = false;//如果鼠标发生了移动，就将moveFlag设置为false,则不再触发onPointerClick方法，即不再绘制点
}
// 鼠标移动
function onPointerMove() {
    moveFlag = true;
}

/**绘制标签 */
function drawLabel(point: any, event: any) {
    
    // 绘制标签展示距离，需要计算起点和终点之间的距离。通过与真实环境下的距离进行换算
    // 设置标签展示位置
    labelText.style.position = 'absolute';
    labelText.style.top = '0';
    labelText.style.color = 'red';
    labelText.style.pointerEvents = 'none';
    document.body.appendChild(labelText);
    // 源代码是构建虚线的时候才实时渲染
    point.onBeforeRender = function () {
        // 设置标签位置，实时渲染
        setLabelPosition(labelText, event);
    }
}
/**动态渲染修改标签位置 */
function setLabelPosition(labelText: any, event: any) {
    let pointLabel = new THREE.Vector3().lerpVectors(vposition, vposition, 0)
    pointLabel = WorldtoScreenPosition(pointLabel, event);
    labelText.style.left = pointLabel.x + 'px';
    labelText.style.top = pointLabel.y + 5 + 'px';
    // let distance = pointsArrV3[1].distanceTo(pointsArrV3[0]);    // 计算显示的数值
    // labelText.innerHTML = distance.toFixed(2) + 'm'; // toFixed把 Number 四舍五入为指定小数位数的数字
    /** 坐标转换，再把vector3坐标转为屏幕坐标*/
    function WorldtoScreenPosition(pos: any, eve: any) {
        // const worldVector = new THREE.Vector3(pos.x, pos.y, pos.z)
        const standardVector = pos.project(window.camera);// 进行投影转换，不太懂为啥转，里面执行了啥操作
        const widthHalf = eve.view.innerWidth / 2;
        const heightHalf = eve.view.innerHeight / 2;
        return {
            x: Math.round(standardVector.x * widthHalf + widthHalf),
            y: Math.round(-standardVector.y * heightHalf + heightHalf),
            z: 1
        }
    }
}